
# -*- coding:utf-8 -*-

import urllib
import urllib2
import socket
import cookielib
# import json
import re
# import os
import time
import datetime
import threading


# global
username = 'hivanchen'
passwd = 'cl2222'
# item_id = '22131868920' ## seven star sword http://item.taobao.com/item.htm?id=22131868920
# item_id = '21832584319' ## money http://item.taobao.com/item.htm?id=21832584319
# item_id = '21832584319'  # 秒杀 http://item.taobao.com/item.htm?spm=0.0.0.0.sdQFJL&id=23229236692
token_list = ''
# debug = True
debug = False


class Taobao():

    def __init__(self):
        self.agent_1 = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13'
        self.agent_2 = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:20.0) Gecko/20100101 Firefox/20.0'


    def get_headers():
        headers = {
            "User-Agent": self.agent_2,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-cn,zh;q=0.5",
            "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7",
            "Keep-Alive": "115",
            "Connection": "keep-alive"
        }
        return headers

    def get_login_dat(self):

        login_data = {
            'TPL_username': username,
            'action': 'Authenticator',
            'event_submit_do_login': 'anything',
            'TPL_redirect_url': '',
            'from': 'tb',
            'fc': '2',
            'style': 'default',
            'css_style': '',
            'tid': '',
            'support': '000001',
            'CtrlVersion': '1,0,0,7',
            'loginType': '3',
            'minititle': '',
            'minipara': '',
            'pstrong': '3',
            'longLogin': '-1',
            'llnick': '',
            'sign': '',
            'need_sign': '',
            'isIgnore': '',
            'popid': '',
            'callback': '',
            'guf': '',
            'not_duplite_str': '',
            'need_user_id': '',
            'poy': '',
            'gvfdcname': '10',
            'from_encoding': ''
        }
        return login_data


    def login(self,source=None):
        # set timeout
        timeout = 20
        timesleep = 10
        socket.setdefaulttimeout(timeout)

        httpHandler = urllib2.HTTPHandler()
        httpsHandler = urllib2.HTTPSHandler()

        # cookie support
        cookie = cookielib.CookieJar()
        cookie_support = urllib2.HTTPCookieProcessor(cookie)

        opener = urllib2.build_opener(cookie_support, httpHandler, httpsHandler)
        urllib2.install_opener(opener)

        url = 'https://login.taobao.com/member/login.jhtml'
        if not source:
            source = urllib2.urlopen(url)
        token_list = source.headers.get('set-cookie').split(';')[3].split('=')[1]  # TODO, get token, need more prefect method
        print token_list
        login_data = self.get_login_data()
        login_data['_tb_token_'] = token_list if token_list else ''
        login_data['TPL_password'] = passwd
        login_data = urllib.urlencode(login_data)
        source = urllib2.Request(url, login_data)
        # conn = urllib2.urlopen(source)
        conn = urllib2.urlopen(url)
        source = conn.read()
        # try:
        #     conn = urllib2.urlopen('http://trade.taobao.com/trade/itemlist/list_bought_items.htm')
        # except Exception:
        #     pass
        # html = conn.read()
        # with open('1.html', 'wu') as f:
        #     f.write(html)

    def login2(self):
        cj = cookielib.CookieJar()

        post_data = urllib.urlencode(
            {
                'CtrlVersion': '1,0,0,7',
                'TPL_password': passwd,
                'TPL_redirect_url': '',
                'TPL_username': username,
                '_tb_token_': '5d7eba30e3b31',
                'action': 'Authenticator',
                'callback': '',
                'css_style': '',
                'event_submit_do_login': 'anything',
                'fc': 2,
                'from': 'tb',
                'from_encoding': '',
                'guf': '',
                'gvfdcname': '',
                'isIgnore': '',
                'llnick': '',
                'loginType': 3,
                'longLogin': 0,
                'minipara': '',
                'minititle': '',
                'need_sign': '',
                'need_user_id': '',
                'not_duplite_str': '',
                'popid': '',
                'poy': '',
                'pstrong': '',
                'sign': '',
                'style': 'default',
                'support': '000001',
                'tid': ''
            }
        )
        path = 'https://login.taobao.com/member/login.jhtml'
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

        opener.addheaders = [('User-agent', self.agent_2)]
        urllib2.install_opener(opener)
        req = urllib2.Request(path, post_data)
        req.addheader = ('Host', 'login.taobao.com')
        req.addheader = ('Referer', 'https://login.taobao.com/member/login.jhtml')
        # req.addheader = ('Content-Length', 414)
        req.addheader = ('Content-Type', 'application/x-www-form-urlencoded')
        # try login
        try:
            conn = urllib2.urlopen(req)
        except HTTPError, e:
            pass  # todo
        # verify login
        conn1 = urllib2.urlopen('http://i.taobao.com/my_taobao.htm')
        html = conn1.read()
        if debug:
            with open('login.html', 'wu') as f:
                f.write(html)

    def buy_now(self, item_id, quantity=1):
        buy_url = 'http://buy.taobao.com/auction/buy_now.jhtml'
        price = '9.80'

        buy_data = {
            'tb_token': token_list,
            'item_url_refer': 'OTHER',
            # 'item_id': '21832584319',
            'item_id': item_id,
            # 'item_id_num': '21832584319',
            'item_id_num': item_id,
            'auction_type': 'b',
            'from': 'item_detail',
            'frm': '',
            'current_price': price,
            'activity': '',
            'auto_post1': '',
            'quantity': '1',
            'skuId': '',
            'skuInfo': '',
            'buyer_from': '',
            'chargeTypeId': '',
        }

        source = urllib2.Request(buy_url, urllib.urlencode(buy_data))
        conn = urllib2.urlopen(source)
        html = conn.read()
        with open('buy.html', 'wu') as f:
                f.write(html)
        # if debug:
        #     with open('buy.html', 'wu') as f:
        #         f.write(html)
        # return html

    def cache(self,item_id):
        try:
            html=self.buy_now(item_id)
            with open('cache.html', 'wu') as f:
                f.write(html)
        except Exception, e:
            print 'cache fail, cannot buy now'
            raise
    
    # read buy.html        
    def read_cache(self, cache_html='buy.html'):
        hiden_data = {}
        with open(cache_html) as f:
            for line in f:
                l = line.strip()
                if l:
                    if l.startswith('<input type="hidden"'):
                        _l = l.replace(' ', '')  # remove blankspace
                        # get name
                        _l1 = _l[_l.find('name='):]
                        if len(_l1) < 2:
                            _l1 = _l[_l.find('id='):]
                        _name = _l1.split('"')[1]
                        # get value
                        _l2 = _l[_l.find('value='):]
                        _value = _l2.split('"')[1]

                        hiden_data[_name] = _value
        # self.cache_data = hiden_data
        return hiden_data

    def submit_deal(self,quantity):
        submit_url = 'http://buy.taobao.com/auction/buy_now.jhtml'
        
        data = self.read_cache()  # 缓存
        # data = self.cache_data  # 缓存
        # print data

        # get the specail name and vaule#########
        specail_name = ''
        specail_value = ''
        for k in data:
            if len(k) > 20:
                specail_name = k
                specail_value = data[k]
        # print specail_name, specail_value
        #
        submit_data = {
            '_tb_token_': token_list,
            'action': 'buynow/smcRoleBuyNowAction',
            'event_submit_do_buy': '1',
            'skuId': data['skuId'],
            'item_id_num': data['item_id_num'],
            'quantity': data['quantity'],
            'date': data['date'],
            'isCheckCode': data['isCheckCode'],
            'encryptString': data['encryptString'],
            'sid': data['sid'],
            'gmtCreate': data['gmtCreate'],
            'saleWinId': data['saleWinId'],
            # 6d7de6305afcc2d173f720bd255512bb  9ad2758e19853f32a69346c01b4e032d
            specail_name: specail_value,
            'actualPaidFee': '9.80',
            'itemReferCode': 'taobao.com',
            '_fm.seller._0.q': data['quantity'],  # how many to buy
            '_fm.seller._0.w': '',
            '_fm.seller._0.s': '',
            '_fm.seller._0.g': '1111',
            '_fm.seller._0.r': '2222',
            '_fm.seller._0.ro': '',
            'anony_enabled': data['anony_enabled'],
            '_fm.seller._0.u': '',
            '_fm.seller._0.c': '8888'

        }

        source = urllib2.Request(submit_url, urllib.urlencode(submit_data))
        conn1 = urllib2.urlopen(source)

        if debug:
            html = conn1.read()
            with open('submit.html', 'wu') as f:
                f.write(html)

    def isOnSale(self, url):
        # s = u'此宝贝已下架'
        target = 'J_ClickCatcher J_LinkBuy'
        conn = urllib2.urlopen(url)
        html = conn.read()

        if debug:
            with open('onSale.html', 'wu') as f:
                f.write(html)
        return html.find(target) == -1

    def buy(self, item_id, quantity=1):
            self.buy_now(item_id, quantity)
            # time.sleep(0.1)
            self.submit_deal(quantity)
            # time.sleep(0.1)
            print 'buy ~~~~~~'

    def secondKill(self, url, item_id, quantity=1):
        # while True:
        for x in xrange(0, 100000):
            try:
                if self.isOnSale(url):
                    if debug:
                        print 'Not on sale now, wait 2 min to check'
                    # time.sleep(2)
                else:
                    if debug:
                        print 'On Sale!!!, start to buy'
                    for y in xrange(0, 50):  # if on sale, buy 3 times
                        # self.buy(item_id, quantity)
                        t = threading.Thread(target=self.buy,args=([item_id]))
                        t.start()
            except Exception, e:
                # raise
                continue

class Buy_thread(threading.Thread):
    def run(self, instanceOfTaobao, item_id):
        instanceOfTaobao.buy(item_id)
        

if __name__ == "__main__":
    # 填要秒杀的链接, 注意, 把url最后id值为购买的id
    # item_id = '21381820676'

    stream = Taobao()
    stream.login2()
    print 'login ok'
    time.sleep(1)

    # stream.cache(item_id)
    # stream.read_cache()
    # stream.buy('21381820676')
    stream.secondKill('http://item.taobao.com/item.htm?id=21381820676','21381820676')



